package cc.rengu.igas.bsps.core.service.trans;

import cc.rengu.igas.bsps.common.constant.BspsAppParamConstant;
import cc.rengu.igas.bsps.common.dao.BspsDevBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsMchntBindInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsQrCodeInfoMapper;
import cc.rengu.igas.bsps.common.dao.BspsUserInfoMapper;
import cc.rengu.igas.bsps.common.dao.impl.BspsDevBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsMchntBindInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsQrCodeInfoMapperImpl;
import cc.rengu.igas.bsps.common.dao.impl.BspsUserInfoMapperImpl;
import cc.rengu.igas.bsps.common.entity.DevBindInfo;
import cc.rengu.igas.bsps.common.entity.MchntBindInfo;
import cc.rengu.igas.bsps.common.entity.QrCodeInfo;
import cc.rengu.igas.bsps.common.entity.UserInfo;
import cc.rengu.igas.bsps.common.enums.BindStatusEnum;
import cc.rengu.igas.bsps.common.enums.RespCodeEnum;
import cc.rengu.igas.bsps.core.realize.PublicDealService;
import cc.rengu.igas.bsps.core.realize.impl.PublicDealServiceImpl;
import cc.rengu.igas.bsps.core.service.base.ManageService;
import cc.rengu.igas.bsps.facade.request.CashierUnBindRequest;
import cc.rengu.igas.bsps.facade.response.CashierUnBindResponse;
import cc.rengu.oltp.service.common.constant.AppConfigConstant;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.*;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @author zhangxuran
 * @version 1.0
 * @date 2020/04/02
 * <p>
 * 1-法人解绑，用户表及绑定关系表逻辑删除，变更为失效状态（注册的用户）
 * 2-店长和收银员解绑，openId更新为空
 */
public class CashierUnBindService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        CashierUnBindRequest cashierUnBindRequest = new CashierUnBindRequest();
        ConvertUtil.convertOutput(cashierUnBindRequest);
        return cashierUnBindRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();
        CashierUnBindRequest cashierUnBindRequest = (CashierUnBindRequest) request;
        CashierUnBindResponse cashierUnBindResponse = new CashierUnBindResponse();
        /*获取请求信息：法人行号，用户标识，商户号，连锁商户号，收银员账号*/
        String instId = cashierUnBindRequest.getHeader().getInstId();
        String userId = cashierUnBindRequest.getUserId();
        String mchntNo = cashierUnBindRequest.getMchntNo();
        String chainMchntNo = cashierUnBindRequest.getChainMchntNo();
        String cashierUserId = cashierUnBindRequest.getCashierId();
        rglog.info("法人行:" + instId + "用户标识:" + userId + "商户号:" + mchntNo + "连锁商户号:" + chainMchntNo + "收银员用户标识ID:" + cashierUserId);
        if (StringUtil.isEmptyOrNull(instId) || StringUtil.isEmptyOrNull(userId) || StringUtil.isEmptyOrNull(mchntNo) || StringUtil.isEmptyOrNull(cashierUserId)) {
            rglog.error("必填性校验失败！");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }
        /*根据商户号和登录账号查询用户信息*/
        BspsUserInfoMapper bspsUserInfoMapper = new BspsUserInfoMapperImpl();
        UserInfo userInfo = bspsUserInfoMapper.selectBspsUserInfoByUserId(instId, cashierUserId);
        if (null == userInfo) {
            rglog.error("查询收银员信息失败!法人行:<{}>，用户ID:<{}>", instId, cashierUserId);
            throw new BizException(RespCodeEnum.GET_USER_INFO_ERROR.getRespCode(), RespCodeEnum.GET_USER_INFO_ERROR.getRespDesc());
        }
        /*判断用户是否有权限进行收银员的解绑操作*/
        PublicDealService publicDealService = new PublicDealServiceImpl();
        boolean authFlag = publicDealService.checkUserOpAuth(instId, mchntNo, userId, cashierUserId);
        if (!authFlag) {
            rglog.error("用户无权限解绑该收银员");
            throw new BizException(RespCodeEnum.USER_NO_AUTHORITY.getRespCode(), RespCodeEnum.USER_NO_AUTHORITY.getRespDesc());
        }
        /*解绑收银员操作:1-收银员信息解绑 2-收银员绑定的二维码解绑  3-收银员绑定的设备解绑*/
        /* 开启数据库事务 */
        String dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(AppConfigConstant.DATABASE_CONF_NODE, AppConfigConstant.OLTP_POOL_NAME);
        String corporation = xmlTreeUtil.getXmlTreeStringValue(AppParamConstant.CORPORATION);
        if (null != corporation && !corporation.isEmpty()) {
            String dbPoolCashNode = corporation.trim() + AppParamConstant.DATABASE_CONF_NODE;
            dbPoolName = XmlConfigUtil.getXmlConfigCacheKeyValue(dbPoolCashNode, AppConfigConstant.OLTP_POOL_NAME);
        }
        DbsUtil dbsUtil = new DbsUtil(dbPoolName);
        dbsUtil.dbsBeginTransaction();
        /*0-用户表信息更新-用户表更新为解绑状态 */
        int iReturnCode;
        BspsMchntBindInfoMapper bspsMchntBindInfoMapper = new BspsMchntBindInfoMapperImpl();
        List<MchntBindInfo> mchntBindInfoList = bspsMchntBindInfoMapper.selectBspsMchntBindInfoListByUserId(instId, userId);
        if (!CollectionUtils.isEmpty(mchntBindInfoList) && mchntBindInfoList.size() == 1) {
            userInfo.setUserStatus("01");
            userInfo.setLastOprId(userId);
            userInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
            iReturnCode = bspsUserInfoMapper.updateBspsUserInfoByPrimaryKey(userInfo);
            if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
                dbsUtil.dbsEndTransaction(false);
                rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
                throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
            }
        }
        /*1-收银员信息解绑--根法人行号+绑定用户ID+绑定商户号 筛选二维码进行更新操作*/
        /*更新信息赋值*/
        MchntBindInfo mchntBindInfo = new MchntBindInfo();
        /*更新为解绑状态*/
        mchntBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
        /*二维码绑定人id*/
        mchntBindInfo.setBindUserId(userInfo.getUserId());
        /*二维码绑定商户*/
        mchntBindInfo.setMchntNo(mchntNo);
        /*法人行信息*/
        mchntBindInfo.setInstId(instId);
        /*最后操作信息*/
        mchntBindInfo.setLastOprId(userId);
        mchntBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        mchntBindInfo.setUnBindDate(DateUtil.getCurrentDate());
        mchntBindInfo.setUnBindTime(DateUtil.getCurrentTime());
        iReturnCode = bspsMchntBindInfoMapper.updateBspsMchntBindInfoStatusByUserIdAndMchntNo(instId, mchntBindInfo);
        if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("收银员解绑失败,iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.SYSTEM_ERROR.getRespCode(), RespCodeEnum.SYSTEM_ERROR.getRespDesc());
        }
        /*3-设备解绑（手机和语音设备）*/
        BspsDevBindInfoMapper bspsDevBindInfoMapper = new BspsDevBindInfoMapperImpl();
        DevBindInfo devBindInfo = new DevBindInfo();
        /*根法人行号+商户号+绑定人员id筛选数据*/
        devBindInfo.setInstId(instId);
        devBindInfo.setBindMchntNo(mchntNo);
        devBindInfo.setBindUserId(userInfo.getUserId());
        devBindInfo.setBindStatus(BindStatusEnum.UNBIND.getStatus());
        /*最后操作信息*/
        devBindInfo.setLastOprId(userId);
        devBindInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        devBindInfo.setUnBindDate(DateUtil.getCurrentDate());
        devBindInfo.setUnBindTime(DateUtil.getCurrentTime());
        iReturnCode = bspsDevBindInfoMapper.updateBspsDevBindInfoStatusByUserIdAndMchntNo(instId, devBindInfo);
        if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
            dbsUtil.dbsEndTransaction(false);
            rglog.error("解绑收银员设备失败,iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.UNBIND_DEVBINDINFO_ERROR.getRespCode(), RespCodeEnum.UNBIND_DEVBINDINFO_ERROR.getRespDesc());
        }
        dbsUtil.dbsEndTransaction(true);

        /*2-二维码信息解绑*/
        BspsQrCodeInfoMapper bspsQrCodeInfoMapper = new BspsQrCodeInfoMapperImpl();
        QrCodeInfo qrCodeInfo = new QrCodeInfo();
        /*根据法人行号，商户号，绑定人筛选解绑二维码数据*/
        qrCodeInfo.setInstId(instId);
        qrCodeInfo.setMchntNo(mchntNo);
        qrCodeInfo.setLogoUrlPath("");
        qrCodeInfo.setRemark3("");
        qrCodeInfo.setUserId(userInfo.getUserId());
        qrCodeInfo.setBindStatus("00");
        /*最后操作信息*/
        qrCodeInfo.setLastOprId(userId);
        qrCodeInfo.setLastUpdateTime(DateUtil.getCurrentDateTime("yyyy-MM-dd HH:mm:ss.SSS"));
        iReturnCode = bspsQrCodeInfoMapper.updateBspsQrCodeInfoStatusByUserIdAndMchntNo(qrCodeInfo);
        if (0 != iReturnCode && BspsAppParamConstant.NODATA_CODE != iReturnCode) {
            rglog.error("二维码解绑失败,iReturnCode:<{}>", iReturnCode);
            throw new BizException(RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespCode(), RespCodeEnum.UPDATE_QRCODE_INFO_ERROR.getRespDesc());
        }
        /* 拼装响应结果 */
        BizResponse<CashierUnBindResponse> bizResponse = new BizResponse<>();
        bizResponse.setRspSysId(AppParamConstant.SYS_ID);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(cashierUnBindResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        CashierUnBindResponse cashierUnBindResponse = (CashierUnBindResponse) bizResponse.getResult();
        ConvertUtil.convertInput(cashierUnBindResponse);
    }
}
